<template>
  <div class="app-container home">
    <el-container style="margin: 0;padding:0;height: 100%">
      <!--      点击气象站点显示的图标-->
      <el-drawer
        title="气象站点信息"
        :visible.sync="markershow"
        direction="ltr"
        size="30%"
        :with-header=false
      >
        <el-container style="padding-top: 20px">
          <el-header>
            <el-icon class="el-icon-alarm-clock" style="color: #409EFF"></el-icon>
            <span style="font-size: 16px;font-weight: 600;color: #409EFF">   {{ markerform.factor.createTime }}</span>
            <span style="font-size: 16px;font-weight: 600;margin-left: 20px">  气象站点详情</span>
          </el-header>
          <el-main>
            <el-col>
              <el-form :model="markerform" label-position="left" label-width="140px">
                <el-form-item label="站点名称">
                  <el-input v-model="markerform.stationName" readonly>
                    <el-button slot="append" icon="el-icon-s-promotion"
                               style="background-color: rgba(64,158,255,0.3)"></el-button>
                  </el-input>
                </el-form-item>
                <el-form-item label="站点级别">
                  <el-radio-group v-model="markerform.stationLevel">
                    <el-radio :label="1">国家级气象站点</el-radio>
                    <el-radio :label="2">地方气象站点</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="地理位置">
                  <el-input v-model='location' readonly>
                    <el-button slot="append" icon="el-icon-location"
                               style="background-color: rgba(64,158,255,0.3)"></el-button>
                  </el-input>
                </el-form-item>
                <el-form-item label="6分钟平均气温">
                  <el-input v-model='temperature' readonly>
                    <el-button slot="append" icon="el-icon-odometer"
                               style="background-color: rgba(64,158,255,0.3)"></el-button>
                  </el-input>
                </el-form-item>
                <el-form-item label="6分钟平均降水">
                  <el-input v-model='this.V50029' readonly>
                    <el-button slot="append" icon="el-icon-light-rain"
                               style="background-color: rgba(64,158,255,0.3)"></el-button>
                  </el-input>
                </el-form-item>
                <el-form-item label="6分钟平均气压">
                  <el-input v-model='this.PRS' readonly>
                    <el-button slot="append" icon="el-icon-loading"
                               style="background-color: rgba(64,158,255,0.3)"></el-button>
                  </el-input>
                </el-form-item>
                <el-form-item label="6分钟相对湿度">
                  <el-input v-model='this.RHU' readonly>
                    <el-button slot="append" icon="el-icon-data-analysis"
                               style="background-color: rgba(64,158,255,0.3)"></el-button>
                  </el-input>
                </el-form-item>
                <el-form-item label="平均2分钟风向">
                  <el-input v-model='this.markerform.factor.win_D_Avg_2mi' readonly>
                    <el-button slot="append" icon="el-icon-wind-power"
                               style="background-color: rgba(64,158,255,0.3);"></el-button>
                  </el-input>
                </el-form-item>
                <el-form-item label="平均2分钟平均风速">
                  <el-input v-model='this.WIN_S_Avg_2mi' readonly>
                    <el-button slot="append" icon="el-icon-timer"
                               style="background-color: rgba(64,158,255,0.3);"></el-button>
                  </el-input>
                </el-form-item>
              </el-form>
            </el-col>
          </el-main>
          <el-footer>
            <el-button type="primary" style="width: 100%" @click="markershow=false">关闭</el-button>
          </el-footer>
        </el-container>
      </el-drawer>
      <el-main style="padding: 0px;margin:0px">
        <div id="map" class="main_map"></div>
        <div
          style="position: absolute; bottom: 30px;left:100px; z-index: 999; display: flex; justify-content: center;align-items: center">
          <el-select v-if="threeWindButtonVisible" v-model="currentHeight" style="color: #409eff"
                     @change="changeWindHeight">
            <el-option
              v-for="item in windHeight"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          <el-button-group style="padding-left: 20px;text-align: center;display: flex;align-items: center">
            <el-date-picker style="margin-right: 13px;width: 200px"
                            v-model="timeForm.currentTimeStamp"
                            type="datetime"
                            placeholder="选择日期时间"
                            @change="handleTimeChange"

            >
            </el-date-picker>

            <!--        自动轮播的时候自动更改样式-->
            <el-button class="window" v-for="(image,index) in nameList"
                       @click="showImageLayer(image,index)"
                       style="width: 5px;margin-right: 10px;padding-left: 10px;padding-right: 10px"
            >
            </el-button>
          </el-button-group>
          <el-button @click="toggleTooltipVisibility" v-if="showTooltipButtonVisible">{{
              showTooltip ? '关闭区县' : '开启区县'
            }}
          </el-button>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import L from "leaflet"
import "leaflet/dist/leaflet.css"
import geoJSONData from "@/assets/geoJSON/hebei.geojson"
import {getLatestStationInfo} from "@/api/system/stationInfo";
import {getLatestLogAndNameList, getLatestLogAndNameListWithCurrentName} from "@/api/system/radarLog";
import moment from "moment";

export default {
  name: "demo3",
  computed: {
    // 站点地理位置
    location() {
      return this.markerform.latitude + "°N," + this.markerform.longitude + "°E"
    },
    // 记录站点六分钟平均气温
    temperature() {
      return this.markerform.factor.tem + " ℃"
    },
    // 记录站点六分钟平均降水
    V50029() {
      return this.markerform.factor.v50029 + " mm/min"
    },
    // 记录站点六分钟平均气压
    PRS() {
      return this.markerform.factor.prs + " hpa"
    },
    // 站点六分钟平均相对湿度
    RHU() {
      return this.markerform.factor.rhu + " %"
    },
    // 平均两分钟平均风速
    WIN_S_Avg_2mi() {
      return this.markerform.factor.win_S_Avg_2mi + " m/s"
    },
  },
  beforeMount() {
    // 初始化连接WebSocket 接收每次新的雷达基文件到达的名称
    const socket = new WebSocket("ws://localhost:8080/websocket");
    socket.onopen = () => {
      console.log("连接成功")
    }
    socket.onmessage = (event) => {
      const message = JSON.parse(event.data);
      if (message.type === "warning") {
        this.message = message.nameList
        this.$message.info("测试成功")
      } else {
        this.$message.info("新的雷达基数据到来")
        getLatestLogAndNameListWithCurrentName().then(res => {
          this.$store.dispatch("SETCURRENTTIMESTAMP", res.data.currentName)
          this.$store.dispatch("SETPREDICTIONLIST", res.data.nameList)
          this.timeForm.currentTimeStamp = moment(res.data.currentName, "YYYYMMDDHHmmss")
          this.nameList = res.data.nameList
          this.changeImageLayer(res.data.currentName)
        })
      }
    }
  },
  mounted() {
    // 初始化获得时间日期
    this.getLogAndNameList()
  },
  created() {
    // 初始化气象站marker的图标信息
    this.markerIcon = L.icon({
      iconUrl: require('@/assets/marker-icon-2x.png'),
      iconSize: [25, 41],
      iconAnchor: [12, 41],  //相对于坐标的偏移位置
    });
  },
  data() {
    return {
      timeForm: {
        currentTimeStamp: null,//当前默认时间戳
      },
      message: null, //预警信息
      currentTimeString: null,//字符串格式的时间戳
      nameList: [],//未来20张的列表
      markershow: false, //是否显示气象站点
      // 点击国家自动气象站绑定到表单上面进行回显
      markerform: {
        stationName: '',
        stationCode: '',
        latitude: '',
        longitude: '',
        stationLevel: null,
        factor: {},
      },
      map: null,  //地图
      imageBounds: [[41.99, 112.0], [36.0, 117.99]],  //回波  降水 冰雹显示图层
      showLabels: true,  // 控制区域名称显示的状态
      stationLayer: null,//气象站点图层
      baseGeoLayer: null, //基础的geoJSON图层
      baseColorMapLayer: null,//基础带标注的底图
      mapImagePrefix: this.$config.mapPath,//带标注的地图图片前缀
      resultImagePrefix: "http://localhost:8081/gis/mapUrl/",  //存放历史数据的图片前缀
      radarEchoLayerGroup: null,  //回波图层组
      radarEchoImageLayer: null,//回波图层
      rainImageLayerGroup: null,//降雨图层组
      windSpeedLayerGroup: null,//风速图层组
      ThreeDWindLayerGroup: null,//三维风图层组
      hailLayerGroup: null,//冰雹图层
      layerControl: null, //图层控制  layerGroup
      markerIcon: null,//气象站点图标
      opacity: 1.0,  //叠加图层的透明度
      threeWindButtonVisible: false,
      windHeight: [
        {label: '1km高度风场', value: '1000'},
        {label: '2km高度风场', value: '2000'},
        {label: '3km高度风场', value: '3000'},
        {label: '4km高度风场', value: '4000'},
        {label: '5km高度风场', value: '5000'},
        {label: '6km高度风场', value: '6000'},
        {label: '7km高度风场', value: '7000'},
        {label: '8km高度风场', value: '8000'},
        {label: '9km高度风场', value: '9000'},
        {label: '10km高度风场', value: '10000'},
      ],
      currentHeight: "1000",
      showTooltip: false,//点击打开或者关闭GeoJSON上面显示的ToolLib
      showTooltipButtonVisible: false,//是否显示控制开启区县Toolib的按钮
    }
  },
  methods: {
    // 地图初始化
    initMap() {
      // geoJSON图层
      this.baseGeoLayer = L.geoJSON(geoJSONData, {
        // 设置背景颜色
        style: this.getStyle,
        onEachFeature: (feature, layer) => {
          // 设置地图上的区域名称显示
          if (feature.properties && feature.properties.name) {
            const center = layer.getBounds().getCenter();  // 获取区域的中心点
            layer.bindTooltip(feature.properties.name, {
              permanent: false,  // 固定显示
              direction: 'center',  // 显示位置
              offset: [0, -10],  // 调整文本的位置，往上偏移
              className: 'leaflet-label'  // 自定义样式类名
            }).openTooltip();
          }
        }
      });
      // 带标注的色彩底图
      this.baseColorMapLayer = L.tileLayer(this.mapImagePrefix + '{z}/{x}/{y}/tile.png', {  //设置瓦片地图图层
        minZoom: 6,
        maxZoom: 14,
        attribution: '© Nuist GIS & 石家庄气象局', //图层注释
      })
      // 声明气象站点图层
      this.stationLayer = L.layerGroup()
      getLatestStationInfo().then(res => {
        // 首次加载站点的同时存储到vuex中
        res.data.forEach(item => {
          // 气象站点添加到图层中
          var marker = L.marker([item.latitude, item.longitude], {
            icon: this.markerIcon,
            opacity: 0.9
          }).addTo(this.stationLayer)  //这里很奇怪 必须在声明就添加到Layergroup中  不然后面无法添加
          // 绑定自动气象站点击事件,弹出嵌套框显示实时气象要素信息
          marker.on('click', () => {
            this.markerform = item
            setTimeout(() => {
              this.markershow = true
            }, 500)
            // 点击平移到站点
            this.map.flyTo([item.latitude, item.longitude])
            this.map.setView([item.latitude, item.longitude], 11)
          })
        })
      })
      // 基础图层
      var baseMaps = {
        "矢量图层底图": this.baseGeoLayer,
        "标注图层底图": this.baseColorMapLayer
      };
      // 添加当前时刻的雷达回波图层
      var radarEchoImageLayer = this.resultImagePrefix + "REFC/" + this.currentTimeString + ".png";
      this.radarEchoLayerGroup = L.layerGroup()
      this.radarEchoLayerGroup.addLayer(L.imageOverlay(radarEchoImageLayer, this.imageBounds, {opacity: this.opacity}),)
      // 添加当前时刻的降雨回波
      var rainImageLayer = this.resultImagePrefix + "QPF/" + this.currentTimeString + ".png"
      this.rainImageLayerGroup = L.layerGroup()
      this.rainImageLayerGroup.addLayer(L.imageOverlay(rainImageLayer, this.imageBounds, {opacity: this.opacity}))
      var windSpeedImageLayer = this.resultImagePrefix + "WindSpeed/" + this.currentTimeString + "00.png"
      this.windSpeedLayerGroup = L.layerGroup()
      this.windSpeedLayerGroup.addLayer(L.imageOverlay(windSpeedImageLayer, this.imageBounds, {opacity: this.opacity}))
      var threeWindImageLayer = this.resultImagePrefix + "ThreeWind/" + this.currentTimeString + "/" + this.currentTimeString + "_1000.png"
      this.ThreeDWindLayerGroup = L.layerGroup()
      this.ThreeDWindLayerGroup.addLayer(L.imageOverlay(threeWindImageLayer, this.imageBounds, {opacity: this.opacity}))
      var hailImageLayer = this.resultImagePrefix + "Hail/" + this.currentTimeString + ".png"
      this.hailLayerGroup = L.layerGroup()
      this.hailLayerGroup.addLayer(L.imageOverlay(hailImageLayer, this.imageBounds, {opacity: this.opacity}))
      var overlayMaps = {
        "石家庄市气象站点": this.stationLayer,
        "雷达回波外推图层": this.radarEchoLayerGroup,
        "降雨估计图层": this.rainImageLayerGroup,
        "风速预估图层": this.windSpeedLayerGroup,
        "三维风场图层": this.ThreeDWindLayerGroup,
        "冰雹反演图层": this.hailLayerGroup
      }
      this.map = L.map('map', {
        center: [38.35194444, 114.71194444],
        zoom: 9,
        layers: [this.baseColorMapLayer, this.radarEchoLayerGroup]
      });
      this.layerControl = L.control.layers(baseMaps, overlayMaps).addTo(this.map);
      // 绑定点击切换叠加的图层和关闭图层事件
      this.map.on("overlayadd", (e) => {
        this.$message.success("显示" + e.name)
        if (e.name === "三维风场图层") {
          this.threeWindButtonVisible = true
        }
      })
      this.map.on("overlayremove", (e) => {
        this.$message.success("关闭" + e.name)
        if (e.name === "三维风场图层") {
          this.threeWindButtonVisible = false
        }
      })
      // 点击切换baseMap的事件
      this.map.on("baselayerchange", (e) => {
        console.log(e)
        if (e.name === "矢量图层底图") {
          this.showTooltipButtonVisible = true
        } else {
          this.showTooltipButtonVisible = false
        }
      })
    },
    // 初始化拉取最新的时间戳和未来预测名称
    getLogAndNameList() {
      getLatestLogAndNameListWithCurrentName().then(res => {
        this.$store.dispatch("SETCURRENTTIMESTAMP", res.data.currentName)
        this.$store.dispatch("SETPREDICTIONLIST", res.data.nameList)
        this.timeForm.currentTimeStamp = res.data.currentName

        // 假设 res.data.currentName 的格式是 YYYYMMDDHHmm
        this.currentTimeString = res.data.currentName
        this.timeForm.currentTimeStamp = moment(res.data.currentName, 'YYYYMMDDHHmm').format('YYYY-MM-DD HH:mm:ss');
        this.nameList = res.data.nameList;
        this.initMap()
      })
    },
    // 点击关闭/打开 GeoJSON图层显示的toolLib
    toggleTooltipVisibility() {
      this.showTooltip = !this.showTooltip;
      // 控制所有图层的 tooltip 显示或隐藏
      this.baseGeoLayer.eachLayer((layer) => {
        if (this.showTooltip) {
          layer.openTooltip();  // 显示tooltip
        } else {
          layer.closeTooltip(); // 隐藏tooltip
        }
      });
    },
    // 点击切换当前时间点的图层
    showImageLayer(image, index) {
      this.currentTimeString = image
      this.timeForm.currentTimeStamp = moment(image, 'YYYYMMDDHHmm').format('YYYY-MM-DD HH:mm')
      this.changeImageLayer(image)
    }
    ,
    /**
     * 切换气象数据的图层源
     * @param image ：表示传入的时间戳
     */
    changeImageLayer(image) {
      var newRadarEchoImageLayer = this.resultImagePrefix + "REFC/" + image + ".png";
      this.clearAndAddNewLayers(this.radarEchoLayerGroup, newRadarEchoImageLayer)
      var newRainImageLayer = this.resultImagePrefix + "QPF/" + image + ".png"
      this.clearAndAddNewLayers(this.rainImageLayerGroup, newRainImageLayer)
      var newWindSpeedImageLayer = this.resultImagePrefix + "WindSpeed/" + image + "00.png"
      this.clearAndAddNewLayers(this.windSpeedLayerGroup, newWindSpeedImageLayer)
      var newThreeWindImageLayer = this.resultImagePrefix + "ThreeWind/" + image + "/" + image + "_1000.png"
      this.clearAndAddNewLayers(this.ThreeDWindLayerGroup, newThreeWindImageLayer)
      var newHailImageLayer = this.resultImagePrefix + "Hail/" + image + ".png"
      this.clearAndAddNewLayers(this.hailLayerGroup, newHailImageLayer)
    },
    // 时间戳字符串转化为日期类型
    formatTime(imagePath) {
      // 第一个时间戳是不携带"/"和".png"的
      const date = moment(imagePath, 'YYYYMMDDHHmm')
      return date.format('YYYY-MM-DD HH:mm')
    }
    ,
    // 点击切换风场高度
    changeWindHeight(newHeight) {
      console.log(newHeight)
      const newHeightUrl = this.resultImagePrefix + "ThreeWind/" + this.currentTimeString + "/" + this.currentTimeString + "_" + newHeight + ".png"
      this.clearAndAddNewLayers(this.ThreeDWindLayerGroup, newHeightUrl)
    }
    ,
    /**
     * 封装图片图层换新图片源的方法
     * @param layerObject
     * @param newImageUrl
     */
    clearAndAddNewLayers(layerObject, newImageUrl) {
      layerObject.clearLayers()
      var newImageLayer = L.imageOverlay(newImageUrl, this.imageBounds, {opacity: this.opacity})
      layerObject.addLayer(newImageLayer)
    }
    ,
    /**
     * 点击切换时间  更新当前时间戳对应的图层
     */
    handleTimeChange(newTime) {
      const date = new Date(newTime);
      const minutes = date.getMinutes();
      // 计算最接近的6分钟的整数倍
      const roundedMinutes = Math.round(minutes / 6) * 6;
      date.setMinutes(roundedMinutes);
      this.timeForm.currentTimeStamp = date
      // 更新绑定的值
      this.currentTimeString = moment(date, 'YYYY-MM-DD HH:mm').format('YYYYMMDDHHmm')
      this.nameList = this.getNextTimestamps(date)
      this.changeImageLayer(this.currentTimeString)
    },
    /**
     * 获取当前时间戳对应的未来预测名称
     */
    getNextTimestamps(initialTime, count = 20, interval = 6) {
      const timestamps = [];
      let currentTime = moment(initialTime, 'YYYYMMDDHHmm');
      for (let i = 0; i <= count; i++) {
        timestamps.push(currentTime.format('YYYYMMDDHHmm'));
        currentTime.add(interval, 'minutes');
      }
      return timestamps;
    },

// 自定义geoJSON的样式
    getStyle(feature) {
      return {
        fillColor: "#8CC5FF", // 背景颜色更淡
        weight: 0.8, // 边框更细
        opacity: 1, // 边框不透明
        color: "#000000", // 边框颜色
        dashArray: "1", // 边框线条样式，设置为虚线
        fillOpacity: 0.5 // 填充的透明度
      };
    }
  }

}
</script>

<style scoped>
.main_map {
  height: 87vh;
  width: 100%;
}
</style>
